package com.jason.fingerprint.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.*;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.beans.DailyReportBean;
import com.jason.fingerprint.beans.LeaveOutBean;
import com.jason.fingerprint.beans.SignInRecordBean;
import com.jason.fingerprint.beans.WorkVisitBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.PreferenceHelper;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.logic.DailyReportSyncLogic;
import com.jason.fingerprint.logic.GetLeaveOutSyncLogic;
import com.jason.fingerprint.logic.HandleSponsorBeanLogic;
import com.jason.fingerprint.logic.InsertVisitSyncLogic;
import com.jason.fingerprint.logic.SignInUploadLogic;
import com.jason.fingerprint.logic.UpdateSignFlagSyncLogic;
import com.jason.fingerprint.logic.UploadToTempSyncLogic;
import com.jason.fingerprint.utils.DataUtils;
import com.jason.fingerprint.utils.FileUtils;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.utils.StringUtils;
import org.kymjs.aframe.utils.SystemTool;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName: InitService
 * @Description: 初始化信息服务处理
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-9-5 13:16:41
 */
public class InitService extends Service {

    private static final String TAG = InitService.class.getSimpleName();

    public static final String ACTION_INIT = "action_init";
    public static final String ACTION_REPEAT_UPLOAD = "action_repeat_upload";

    private static final int REPEAT_TIME = 6 * 60 * 60 * 1000;//轮询自动上传时间。6个小时

    private static final int CLEAR_DATE_TIME = 15;//清除数据间隔时间

    private InitBroadcastReceiver mInitBroadcastReceiver;

    private AppContext mAppContext;

    private KJDB mKJDB;

    public static AlarmManager mAlarmManager;
    private Timer mTimer;
    private TimerTask mTimerTask;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand");
        if (intent != null && !StringUtils.isEmpty(intent.getAction())){
            Log.i(TAG,"onStartCommand action:" + intent.getAction());
            uploadData();
        }
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        mAppContext = AppContext.getInstance();
        mKJDB = AppContext.mInstance.getKjdb();
        mInitBroadcastReceiver = new InitBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_INIT);
        intentFilter.addAction(ACTION_REPEAT_UPLOAD);
        this.registerReceiver(mInitBroadcastReceiver,intentFilter);
        //开始处理
        sendBroadcast(new Intent(ACTION_INIT));
        sendUpdateBroadcastRepeat();
//        initTimer();
    }

    private void initTimer(){
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG,"ACTION_REPEAT_UPLOAD");
                mUploadDataHandler.handleMessage(mUploadDataHandler.obtainMessage(200));
            }
        };
        //开始一个定时任务
        mTimer.schedule(mTimerTask, 0, 30000);
    }

    private Handler mUploadDataHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Looper.prepare();
            uploadData();
            Looper.loop();
        }
    };


    private void uploadData(){
        if (!SystemTool.checkNet(this)) {
            return;
        }
        //同步请假签到
        (new GetLeaveOutSyncLogic(mAppContext,new Handler(),false)).execute();
        //同步集中教育
        new HandleSponsorBeanLogic(mAppContext,
                new Handler(), false).getTodayActivities("0");
        //同步社区服务
        new HandleSponsorBeanLogic(mAppContext,
                new Handler(), false).getTodayActivities("1");

        //社区服务，教育学习
        (new SignInUploadLogic(mAppContext,mUploadHandler, "")).execute();
        //日常报到
        (new DailyReportSyncLogic(
                mAppContext, new Handler(), false)).execute();
        //外出请假
        (new UpdateSignFlagSyncLogic(
                mAppContext, mUpdateSignFlagHandler, true)).execute();

        //工作走访
        (new InsertVisitSyncLogic(mAppContext,
                mInsertVisitHandler, true)).execute();
    }

    private void sendUpdateBroadcastRepeat(){
        mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent =new Intent(InitService.this,com.jason.fingerprint.receiver.InitBroadcastReceiver.class);
        intent.setAction(ACTION_REPEAT_UPLOAD);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        //6个小时一个周期，不停的发送广播
        mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), REPEAT_TIME, pendingIntent);
    }



    private void deleteDataFromTable(){
        Log.i(TAG,"deleteDataFromTable begin...");
        PreferenceHelper.setDeleteTableToday(mAppContext, DataUtils.getToday());
        //删除日常签到信息
        try{
            mKJDB.deleteByWhere(DailyReportBean.class,"state = 2");
        } catch (Exception e){
            e.printStackTrace();
        }
        //删除矫正人员签到信息
        try{
            mKJDB.deleteByWhere(SignInRecordBean.class,"state = 2");
        } catch (Exception e){
            e.printStackTrace();
        }

        //删除矫正人员请假
        try{
            mKJDB.deleteByWhere(LeaveOutBean.class,"state = 2");
        } catch (Exception e){
            e.printStackTrace();
        }

        //删除工作走访
        try{
            mKJDB.deleteByWhere(WorkVisitBean.class,"state = 2");
        } catch (Exception e){
            e.printStackTrace();
        }

        //删除图片信息
        try {
            //获取所有的已上传图片
            List<ImageOrAudioBean> imageOrAudios =  mKJDB.findAllByWhere(ImageOrAudioBean.class,"state = 2");
            if (imageOrAudios != null && !imageOrAudios.isEmpty()){
                for (ImageOrAudioBean bean : imageOrAudios){
                    FileUtils.deleteFile(bean.getFilePath());
                    mKJDB.delete(bean);
                }
            }
        }catch (Exception e){

        }

    }

    public class InitBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG,"action:" + action);
            if (ACTION_INIT.equals(action)){
                // 判断是否是当前第一次进入程序。执行上传记录
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String day = PreferenceHelper.getFirstToday(mAppContext);
                        Log.i(TAG,"day:" + day);
                        Log.i(TAG,"getToday:" + DataUtils.getToday());
                        if (!DataUtils.getToday().equals(day)){
                            SignInUploadLogic logic = new SignInUploadLogic(mAppContext,mUploadHandler, "");
                            logic.execute();
                        }

                        // 删除1个月之前未上传记录
                        String date = PreferenceHelper.getDeleteTableToday(mAppContext);
                        if (TextUtils.isEmpty(date)){
                            deleteDataFromTable();
                        }else{
                            if (DataUtils.daysBetween(DataUtils.getToday(),date) >= 7){
                                deleteDataFromTable();
                            }
                        }
                    }
                }).start();

            }
        }
    }

    //外出请假
    private Handler mInsertVisitHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            (new UploadToTempSyncLogic(
                    mAppContext, new Handler(), false, UploadToTempSyncLogic.SERVICE.SERVICE_WORK_VISIT)).execute();
        }
    };

    //外出请假
    private Handler mUpdateSignFlagHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            (new UploadToTempSyncLogic(
                    mAppContext, new Handler(), false, UploadToTempSyncLogic.SERVICE.SERVICE_LEAVE_OUT)).execute();
        }
    };

    private Handler mUploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i(TAG,"what:" + msg.what);
            switch (msg.what) {
                case UIHelper.SIGNIN_UPLOAD_SUCCESS:
                    //TODO 上传资源
                    uploadImageOrAudio();
                    break;
                case UIHelper.SIGNIN_UPLOAD_ERROR:
                case UIHelper.SIGNIN_UPLOAD_FAIL:
                    // 上传签到失败 --不区别失败的种类
                    uploadImageOrAudio();
                    break;
                case UIHelper.FILE_UPLOAD_SUCCESS:
                    PreferenceHelper.setFirstToday(mAppContext,DataUtils.getToday());
                    break;
                case UIHelper.FILE_UPLOAD_FAIL:
                    PreferenceHelper.setFirstToday(mAppContext,DataUtils.getToday());
                    break;
                default:
                    break;
            }
        }

    };

    private void uploadImageOrAudio() {
        UploadToTempSyncLogic logic = new UploadToTempSyncLogic(
                mAppContext, mUploadHandler, true, "");
        logic.execute();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG,"onBind");
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");
        try {
            this.unregisterReceiver(mInitBroadcastReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mTimer != null){
            mTimer.cancel();
        }
        //不让用户强制关闭服务
        startService(new Intent(this, InitService.class));
    }
}
